package com.ruoyi.orderEat.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.RedisUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.websocket.WebSocketServer;
import com.ruoyi.orderEat.domain.*;
import com.ruoyi.orderEat.mapper.OrderAssociatedMapper;
import com.ruoyi.orderEat.mapper.ShopFlavourMapper;
import com.ruoyi.orderEat.service.IShopInfoService;
import com.ruoyi.orderEat.web.OrderStateCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.orderEat.mapper.OrderInfoMapper;
import com.ruoyi.orderEat.service.IOrderInfoService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单信息Service业务层处理
 *
 * @author dinghao
 * @date 2023-12-06
 */
@Service
public class OrderInfoServiceImpl implements IOrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderAssociatedMapper orderAssociatedMapper;

    @Autowired
    private IShopInfoService shopInfoService;

    @Autowired
    private ShopFlavourMapper shopFlavourMapper;

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 查询订单信息
     *
     * @param orderId 订单信息主键
     * @return 订单信息
     */
    @Override
    public OrderInfo selectOrderInfoByOrderId(Long orderId) {
        return orderInfoMapper.selectOrderInfoByOrderId(orderId);
    }

    @Override
    public Integer queryWxTable() {
        Long wxUserId = SecurityUtils.getWxUserId();
        String userKey = USER_TABLE + wxUserId;
        Integer tableId = (Integer) redisUtil.get(userKey);
        return tableId;
    }

    @Override
    public PageInfo<OrderInfo> selectOrderInfos(OrderInfo orderInfo) {
        List<OrderInfo> orderInfos = orderInfoMapper.selectOrderInfoList(orderInfo);
        return new PageInfo<>(orderInfos);
    }

    /**
     * 查询订单信息列表
     *
     * @param orderInfo 订单信息
     * @return 订单信息
     */
    @Override
    public List<OrderInfoVO> selectOrderInfoList(OrderInfo orderInfo, Integer pageNum, Integer pageSize) {
        Long userId = SecurityUtils.getWxUserId() == null ? SecurityUtils.getUserId() : SecurityUtils.getWxUserId();
        if ((orderInfo.getOrderStatus().equals(0) && orderInfo.getTableId() == null) ||
                (orderInfo.getOrderStatus().equals(0) && orderInfo.getTableId() == 0)) {
            return null;
        }
        if (orderInfo.getOrderStatus().equals(1)) {
            orderInfo.setUserId(userId);
            orderInfo.setTableId(null);
        }
        int offset = (pageNum - 1) * pageSize;
        List<OrderInfoVO> orderInfoVOS = orderInfoMapper.selectOrderInfoVOList(orderInfo, offset, pageSize);
        for (OrderInfoVO orderInfoVO : orderInfoVOS) {
            orderInfoVO.setBarbecueShopName("二师兄烧烤");
            Integer count = orderInfoVO.getShopCartList().stream().map(ShopCart::getShopNum).reduce(0, Integer::sum);
            orderInfoVO.setShopCount(count);
            for (ShopCart shopCart : orderInfoVO.getShopCartList()) {
                String flavourId = shopCart.getFlavourId();
                if (flavourId!=null){
                    String[] flavourIds = flavourId.split("-");
                    StringBuilder flavour = new StringBuilder();
                    for (int i = 0; i < flavourIds.length; i++) {
                        ShopFlavour shopFlavour = shopFlavourMapper.selectShopFlavourByFlavourId(Long.parseLong(flavourIds[i]));
                        String flavourName = shopFlavour.getFlavourName();
                        if (i>0){
                            flavour.append("、"+flavourName);
                        }else {
                            flavour.append(flavourName);
                        }
                    }
                    shopCart.setFlavourName(flavour.toString());
                }
            }
        }
        return orderInfoVOS;
    }

    @Override
    public List<ShopCart> selectOrderDetailList(Long orderId) {
        List<ShopCart> shopCartList = orderAssociatedMapper.getShopCartList(orderId);
        for (ShopCart shopCart : shopCartList) {
            String flavourId = shopCart.getFlavourId();
            if (flavourId!=null&&!flavourId.equals("")) {
                StringBuilder flavour = new StringBuilder();
                if (flavourId.contains("-")) {
                    String[] flavourIds = flavourId.split("-");
                    for (int i = 0; i < flavourIds.length; i++) {
                        if (i > 0) {
                            ShopFlavour shopFlavour = shopFlavourMapper.selectShopFlavourByFlavourId(Long.parseLong(flavourIds[i]));
                            flavour.append("、" + shopFlavour.getFlavourName());
                        } else {
                            ShopFlavour shopFlavour = shopFlavourMapper.selectShopFlavourByFlavourId(Long.parseLong(flavourIds[i]));
                            flavour.append(shopFlavour.getFlavourName());
                        }
                    }
                    shopCart.setFlavourName(flavour.toString());
                } else {
                    ShopFlavour shopFlavour = shopFlavourMapper.selectShopFlavourByFlavourId(Long.parseLong(flavourId));
                    flavour.append(shopFlavour.getFlavourName());
                    shopCart.setFlavourName(flavour.toString());
                }
            }
        }
        return shopCartList;
    }

    @Override
    public List<OrderListVO> selectOrderList(OrderInfo orderInfo) {
        List<OrderListVO> orderListVOS = orderInfoMapper.selectOrderList(orderInfo);
        orderListVOS.parallelStream().forEach(item -> {
            item.setOrderStatusName(OrderStateCode.getDesc(item.getOrderStatus()));
            if (item.getOrderListVOList().size() > 0) {
                item.getOrderListVOList().forEach(orderListVO -> {
                    orderListVO.setOrderStatusName(OrderStateCode.getDesc(orderListVO.getOrderStatus()));
                    orderListVO.setRemark("结算后删除");
                });
            }
        });
        return orderListVOS;
    }

    @Override
    public void saveTableAndUser(Integer tableId) {
        Long wxUserId = SecurityUtils.getWxUserId();
        String userKey = USER_TABLE + wxUserId;
        redisUtil.setEx(userKey, tableId, 24, TimeUnit.HOURS);
    }

    /**
     * 程序递归获得订单列表
     **/
    public List<OrderListVO> search(OrderInfo orderInfo) {
        List<OrderInfo> orderInfos = orderInfoMapper.selectOrderInfoList(orderInfo);
        List<OrderListVO> orderListVOs = orderInfos.stream().map(item -> {
            OrderListVO orderListVO = new OrderListVO();
            BeanUtils.copyProperties(item, orderListVO);
            return orderListVO;
        }).collect(Collectors.toList());
        List<OrderListVO> returnList = new ArrayList<>();
        for (OrderListVO orderListVO : orderListVOs) {
            if (orderListVO.getParentId().equals(0)) {
                recursionFn(orderListVOs, orderListVO);
                returnList.add(orderListVO);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t    子节点
     */
    private void recursionFn(List<OrderListVO> list, OrderListVO t) {
        // 得到子节点列表
        List<OrderListVO> childList = getChildList(list, t);
        t.setOrderListVOList(childList);
        for (OrderListVO tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<OrderListVO> getChildList(List<OrderListVO> list, OrderListVO t) {
        List<OrderListVO> tlist = new ArrayList<>();
        Iterator<OrderListVO> it = list.iterator();
        while (it.hasNext()) {
            OrderListVO n = (OrderListVO) it.next();
            if (n.getParentId().longValue() == t.getOrderId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<OrderListVO> list, OrderListVO t) {
        return getChildList(list, t).size() > 0;
    }


    /**
     * 小程序新增订单信息
     *
     * @param orderShop
     */
    @Override
    @Transactional
    public int insertOrderInfo(OrderShop orderShop) {
        Long userId = SecurityUtils.getWxUserId() == null ? SecurityUtils.getUserId() : SecurityUtils.getWxUserId();
        List<ShopCart> shopCartList = orderShop.getShopCartList();
        Integer tableId = orderShop.getTableId();
        Integer dinerNum = orderShop.getDinerNum();
        StringBuilder newOrderNumberBuilder = new StringBuilder(NEW_NAME);
        OrderInfo order = new OrderInfo();
        order.setTableId(tableId);
        order.setOrderStatus(OrderStateCode.DINING.getCode());
        List<OrderInfo> orderInfos = orderInfoMapper.selectOrderInfoList(order);
        //如果当前餐桌号与订单状态为“用餐中”的查询结果不为空则修改原有订单产品同时生成追加订单和追加商品，否则就新增订单产品
        if (orderInfos.size() > 0) {
            Long orderId = orderInfos.get(0).getOrderId();
            BigDecimal oldOrderAmount = orderInfos.get(0).getOrderAmount();
            List<OrderAssociated> orderAssociatedList = orderAssociatedMapper.selectByOrderId(orderId);
            //如果新增商品原订单没有则新增商品
            List<Long> shopIds = orderAssociatedList.parallelStream().map(OrderAssociated::getShopId).collect(Collectors.toList());
            List<String> markIds = orderAssociatedList.parallelStream().map(orderAssociated -> {
                String flavourId = orderAssociated.getFlavourId();
                StringBuilder flavour = new StringBuilder(String.valueOf(orderAssociated.getShopId()));
                flavour.append("-" + flavourId);
                return flavour.toString();
            }).collect(Collectors.toList());
            List<OrderAssociated> newOrderAssociatedList = new ArrayList<>();
            for (ShopCart shopCart : shopCartList) {
                Integer shopNum = shopCart.getShopNum();
                if (shopCart.getMarkId() != null && (!markIds.contains(shopCart.getMarkId()))) {
                    OrderAssociated newOrderAssociated = addNewOrderAssociated(shopNum, orderId, shopCart, userId);
                    newOrderAssociatedList.add(newOrderAssociated);
                } else if (shopCart.getMarkId() == null && (!shopIds.contains(shopCart.getShopId()))) {
                    OrderAssociated newOrderAssociated = addNewOrderAssociated(shopNum, orderId, shopCart, userId);
                    newOrderAssociatedList.add(newOrderAssociated);
                }
                //如果新增商品原订单已有则在原订单基础上新增商品数量
                for (OrderAssociated orderAssociated : orderAssociatedList) {
                    String flavourId = orderAssociated.getFlavourId();
                    StringBuilder mark = new StringBuilder(String.valueOf(orderAssociated.getShopId()));
                    mark.append("-" + flavourId);
                    if (shopCart.getMarkId() == null && shopCart.getShopId().equals(orderAssociated.getShopId())) {
                        updateOrderAssociated(orderAssociated, shopNum);
                    } else if (shopCart.getMarkId() != null && (shopCart.getShopId().equals(orderAssociated.getShopId()) && shopCart.getMarkId().equals(mark.toString()))) {
                        updateOrderAssociated(orderAssociated, shopNum);
                    }
                }
            }
            if (newOrderAssociatedList.size() > 0) {
                orderAssociatedMapper.insertBatch(newOrderAssociatedList);
            }
            //增加追加订单信息
            if (orderInfoMapper.countByOrderStatus(OrderStateCode.APPEND.getCode(), orderShop.getTableId().longValue()) == 0) {
                String newOrderNumber = newOrderNumberBuilder.append(1).toString();
                addOrder(newOrderNumber, orderId.intValue(), tableId, dinerNum, orderId.intValue(), OrderStateCode.APPEND.getCode(), oldOrderAmount, shopCartList, userId);
            } else {
                String newOrderNumber = newOrderNumberBuilder.append(orderInfoMapper.countByOrderStatus(OrderStateCode.APPEND.getCode(), orderShop.getTableId().longValue()) + 1).toString();
                addOrder(newOrderNumber, orderId.intValue(), tableId, dinerNum, orderId.intValue(), OrderStateCode.APPEND.getCode(), oldOrderAmount, shopCartList, userId);
            }
            //新增订单
        } else {
            String orderNum = UUID.randomUUID().toString().replace("-", "");
            addOrder(orderNum, null, tableId, dinerNum, 0, OrderStateCode.DINING.getCode(), null, shopCartList, userId);
        }
        //清空购物车
        shopInfoService.delAllCart(shopCartList, tableId);
        // 通知前端
        try {
            WebSocketServer.sendInfo("add", null);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return 1;
    }

    @Override
    public int ceshi(OrderShop orderShop) {
        List<ShopCart> shopCartList = orderShop.getShopCartList();
        Integer tableId = orderShop.getTableId();
        OrderInfo order = new OrderInfo();
        order.setTableId(tableId);
        order.setOrderStatus(OrderStateCode.DINING.getCode());
        List<OrderInfo> orderInfos = orderInfoMapper.selectOrderInfoList(order);
        Long orderId = orderInfos.get(0).getOrderId();

        return 0;
    }

    /**
     * 修改的订单商品的关联关系信息
     **/
    private void updateOrderAssociated(OrderAssociated orderAssociated, Integer shopNum) {
        Integer count = orderAssociated.getCount();
        count += shopNum;
        orderAssociated.setCount(count);
        orderAssociatedMapper.updateByPrimaryKey(orderAssociated);
    }
    /**
     * 增加新的订单商品的关联关系
     **/
    private OrderAssociated addNewOrderAssociated(Integer shopNum, Long orderId, ShopCart shopCart, Long userId) {
        OrderAssociated newOrderAssociated = new OrderAssociated();
        newOrderAssociated.setCount(shopNum);
        newOrderAssociated.setOrderId(orderId);
        newOrderAssociated.setShopId(shopCart.getShopId());
        if (shopCart.getMarkId() != null) {
            String flavourId = shopCart.getMarkId().substring(shopCart.getMarkId().indexOf("-") + 1);
            newOrderAssociated.setFlavourId(flavourId);
        }
        newOrderAssociated.setCreateBy(String.valueOf(userId));
        newOrderAssociated.setCreateTime(new Date());
        return newOrderAssociated;
    }

    /**
     * 增加订单与订单商品
     **/
    private void addOrder(String orderNumber, Integer orderId, Integer tableId, Integer dinerNum, Integer parentId, Integer oderStatus, BigDecimal oldOrderAmount, List<ShopCart> shopCartList, Long userId) {
        BigDecimal orderAmount = new BigDecimal(0);
        List<OrderAssociated> orderAssociatedList = new ArrayList<>();
        for (ShopCart shopCart : shopCartList) {
            BigDecimal saleAmount = shopCart.getSaleAmount();
            orderAmount = orderAmount.add(saleAmount);
            OrderAssociated orderAssociated = new OrderAssociated();
            String oldMarkId = shopCart.getMarkId();
            if (oldMarkId != null && !oldMarkId.isEmpty()) {
                String[] markIds = shopCart.getMarkId().split("-");
                List<String> mark = Arrays.stream(markIds).filter(item -> !item.equals(String.valueOf(shopCart.getShopId()))).collect(Collectors.toList());
                String flavourId = String.join("-", mark);
                orderAssociated.setFlavourId(flavourId);
            }
            orderAssociated.setCount(shopCart.getShopNum());
            orderAssociated.setShopId(shopCart.getShopId());
            orderAssociated.setCreateBy(String.valueOf(userId));
            orderAssociated.setCreateTime(new Date());
            orderAssociatedList.add(orderAssociated);
        }
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderAmount(orderAmount);
        orderInfo.setOrderNumber(orderNumber);
        orderInfo.setParentId(parentId);
        orderInfo.setOrderStatus(oderStatus);
        orderInfo.setTableId(tableId);
        orderInfo.setDinerNum(dinerNum);
        orderInfo.setUserId(userId);
        orderInfo.setCreateBy(String.valueOf(userId));
        orderInfo.setCreateTime(new Date());
        orderInfoMapper.insertOrderInfo(orderInfo);
        orderAssociatedList.forEach(item -> item.setOrderId(orderInfo.getOrderId()));
        orderAssociatedMapper.insertBatch(orderAssociatedList);
        if (orderId != null) {
            OrderInfo amountOrder = new OrderInfo();
            amountOrder.setOrderId(orderId.longValue());
            oldOrderAmount = oldOrderAmount.add(orderAmount);
            amountOrder.setOrderAmount(oldOrderAmount);
            orderInfoMapper.updateOrderInfo(amountOrder);
        }
    }

    @Override
    public int insertOrderList(OrderShop orderShop) {
        Long userId = SecurityUtils.getUserId();
        UUID orderNum = UUID.randomUUID();
        StringBuilder newOrderName = new StringBuilder(NEW_NAME);
        OrderInfo order = new OrderInfo();
        order.setTableId(orderShop.getTableId());
        order.setOrderStatus(OrderStateCode.DINING.getCode());
        List<OrderInfo> orderInfos = orderInfoMapper.selectOrderInfoList(order);
        if (orderInfos.size() > 0) {
            Long orderId = orderInfos.get(0).getOrderId();
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setParentId(orderId.intValue());
            orderInfo.setOrderAmount(new BigDecimal(12));
            if (orderInfoMapper.countByOrderStatus(OrderStateCode.APPEND.getCode(), orderShop.getTableId().longValue()) == 0) {
                orderInfo.setOrderNumber(newOrderName.append(1).toString());
            } else {
                orderInfo.setOrderNumber(newOrderName.append(orderInfoMapper.countByOrderStatus(OrderStateCode.APPEND.getCode(), orderShop.getTableId().longValue()) + 1).toString());
            }
            orderInfo.setOrderStatus(OrderStateCode.APPEND.getCode());
            orderInfo.setTableId(orderShop.getTableId());
            orderInfo.setDinerNum(orderShop.getDinerNum());
            orderInfo.setUserId(userId);
            orderInfo.setCreateBy(String.valueOf(userId));
            orderInfo.setCreateTime(new Date());
            orderInfoMapper.insertOrderInfo(orderInfo);

        } else {
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setOrderAmount(new BigDecimal(11));
            orderInfo.setParentId(0);
            orderInfo.setOrderNumber(orderNum.toString().replace("-", ""));//UUID除掉横
            orderInfo.setOrderStatus(OrderStateCode.DINING.getCode());
            orderInfo.setTableId(orderShop.getTableId());
            orderInfo.setDinerNum(orderShop.getDinerNum());
            orderInfo.setUserId(userId);
            orderInfo.setCreateBy(String.valueOf(userId));
            orderInfo.setCreateTime(new Date());
            orderInfoMapper.insertOrderInfo(orderInfo);
        }
        // 通知前端
        try {
            WebSocketServer.sendInfo("add", null);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return 1;
    }

    /**
     * 结算订单
     *
     * @param orderInfo 订单信息
     * @return 结果
     */
    @Override
    public void updateOrderInfo(OrderInfo orderInfo) {
        orderInfo.setUpdateTime(DateUtils.getNowDate());
        orderInfo.setOrderStatus(OrderStateCode.PAID.getCode());
        orderInfoMapper.updateOrderInfo(orderInfo);

    }

    @Override
    @Transactional
    public void updateWxOrder(OrderInfo orderInfo) {
        Long userId = SecurityUtils.getWxUserId() == null ? SecurityUtils.getUserId() : SecurityUtils.getWxUserId();
        orderInfo.setOrderStatus(OrderStateCode.AWAITING.getCode());
        orderInfo.setUpdateTime(DateUtils.getNowDate());
        orderInfo.setUpdateBy(String.valueOf(userId));
        orderInfo.setUserId(userId);
        orderInfoMapper.updateOrderInfo(orderInfo);
        List<OrderInfo> orderInfoList = orderInfoMapper.selectByParentId(orderInfo.getOrderId());
        Long[] orderIds = orderInfoList.parallelStream().map(OrderInfo::getOrderId).toArray(Long[]::new);
        if (orderIds.length > 0) {
            orderInfoMapper.deleteOrderInfoByOrderIds(orderIds);
            orderAssociatedMapper.deleteByOrderIds(orderIds);
        }
        // 通知前端
        try {
            WebSocketServer.sendInfo("edit", null);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    @Transactional
    public void updateOrderDetail(List<ShopCart> orderDetailList, Long orderId) {
        orderAssociatedMapper.deleteByOrderId(orderId);
        BigDecimal orderAmount = new BigDecimal(0);
        List<OrderAssociated> orderAssociatedList = new ArrayList<>();
        for (ShopCart shopCart : orderDetailList) {
            OrderAssociated orderAssociated = new OrderAssociated();
            orderAssociated.setOrderId(orderId);
            orderAssociated.setShopId(shopCart.getShopId());
            orderAssociated.setCount(shopCart.getShopNum());
            if (shopCart.getShopNum() != 0) {
                orderAssociatedList.add(orderAssociated);
            }
            Integer shopNum = shopCart.getShopNum();
            BigDecimal shopAmount = shopCart.getShopAmount();
            orderAmount = orderAmount.add(shopAmount.multiply(new BigDecimal(shopNum)));
        }
        orderAssociatedMapper.insertBatch(orderAssociatedList);
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderAmount(orderAmount);
        orderInfo.setOrderId(orderId);
        orderInfoMapper.updateOrderInfo(orderInfo);
    }

    @Override
    @Transactional
    public void updateOrderAssociateDetail(OrderInfoVO orderInfoVO) {
        //对比修改后的订单商品信息，如果订单商品数量变更，将变更差值存入Map中，然后将追加订单删除并重新添加
        Long orderId = orderInfoVO.getOrderId();
        List<ShopCart> shopCartList = orderInfoVO.getShopCartList();
        List<OrderAssociated> newOrderAssociatedList = new ArrayList<>();
        List<OrderAssociated> orderAssociatedList = orderAssociatedMapper.selectByOrderId(orderId);
        List<Map<String, Object>> changeShopList = new ArrayList<>();
        for (ShopCart shopCart : shopCartList) {
            for (OrderAssociated orderAssociated : orderAssociatedList) {
                if (shopCart.getShopId().equals(orderAssociated.getShopId()) && !shopCart.getShopNum().equals(orderAssociated.getCount())) {
                    int difference = orderAssociated.getCount() - shopCart.getShopNum();
                    if (difference < 0) {
                        throw new ServiceException("后台只能减商品不能增加商品", HttpStatus.BAD_REQUEST);
                    }
                    Map<String, Object> changeShop = new HashMap<>();
                    changeShop.put("shopId", shopCart.getShopId());
                    changeShop.put("difference", difference);
                    changeShopList.add(changeShop);
                }
            }
            OrderAssociated orderAssociated = new OrderAssociated();
            orderAssociated.setOrderId(orderId);
            orderAssociated.setShopId(shopCart.getShopId());
            orderAssociated.setCount(shopCart.getShopNum());
            if (shopCart.getShopNum() != 0) {
                newOrderAssociatedList.add(orderAssociated);
            }
        }
        orderAssociatedMapper.deleteByOrderId(orderId);
        orderAssociatedMapper.insertBatch(newOrderAssociatedList);
        //获得主订单对应的商品信息，如果追加订单商品有变化就将订单商品数量变更差值进行修改，如果差值计算完成为0就删除那个商品
        Integer parentId = orderInfoMapper.selectOrderInfoByOrderId(orderId).getParentId();
        List<OrderAssociated> mainOrderAssociatedList = orderAssociatedMapper.selectByOrderId(parentId.longValue());
        for (OrderAssociated orderAssociated : mainOrderAssociatedList) {
            for (Map<String, Object> changeShop : changeShopList) {
                Long shopId = (Long) changeShop.get("shopId");
                Integer difference = (Integer) changeShop.get("difference");
                if (orderAssociated.getShopId().equals(shopId)) {
                    OrderAssociated newOrderAssociated = new OrderAssociated();
                    BeanUtils.copyProperties(orderAssociated, newOrderAssociated);
                    int differenceCount = newOrderAssociated.getCount() - difference;
                    if (differenceCount == 0) {
                        orderAssociatedMapper.deleteByPrimaryKey(orderAssociated.getOrderAssociatedId());
                    } else {
                        newOrderAssociated.setCount(newOrderAssociated.getCount() - difference);
                        orderAssociatedMapper.updateByPrimaryKey(newOrderAssociated);
                    }
                }
            }
        }
        countAndUpdateAmount(parentId.longValue());
        countAndUpdateAmount(orderId);
    }

    /**
     * 计算订单商品的价格，然后修改订单
     **/
    private void countAndUpdateAmount(Long orderId) {
        List<OrderAssociated> orderAssociatedList = orderAssociatedMapper.selectByOrderId(orderId);
        BigDecimal orderAmount = new BigDecimal(0);
        for (OrderAssociated orderAssociated : orderAssociatedList) {
            Integer count = orderAssociated.getCount();
            ShopInfo shopInfo = shopInfoService.selectShopInfoByShopId(orderAssociated.getShopId());
            BigDecimal shopAmount = shopInfo.getShopAmount();
            orderAmount = orderAmount.add(shopAmount.multiply(new BigDecimal(count)));
        }
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderId(orderId);
        orderInfo.setOrderAmount(orderAmount);
        orderInfoMapper.updateOrderInfo(orderInfo);
    }

    /**
     * 批量删除订单信息
     *
     * @param orderIds 需要删除的订单信息主键
     * @return 结果
     */
    @Override
    public int deleteOrderInfoByOrderIds(Long[] orderIds) {
        return orderInfoMapper.deleteOrderInfoByOrderIds(orderIds);
    }

    /**
     * 删除订单信息信息
     *
     * @param orderId 订单信息主键
     * @return 结果
     */
    @Override
    public int deleteOrderInfoByOrderId(Long orderId) {
        return orderInfoMapper.deleteOrderInfoByOrderId(orderId);
    }

    @Override
    @Transactional
    public void deleteOrderInfo(Long orderId) {
        Long[] orderIds = orderInfoMapper.selectByParentId(orderId).parallelStream().map(OrderInfo::getOrderId).toArray(Long[]::new);
        if (orderIds.length > 0) {
            orderInfoMapper.deleteOrderInfoByOrderIds(orderIds);
            orderAssociatedMapper.deleteByOrderIds(orderIds);
        }
        orderInfoMapper.deleteOrderInfoByOrderId(orderId);
        orderAssociatedMapper.deleteByOrderId(orderId);
    }

    @Override
    @Transactional
    public void deleteOrderAssociateByOrderAssociatedId(Long orderId) {
        List<OrderAssociated> orderAssociatedList = orderAssociatedMapper.selectByOrderId(orderId);//查询子订单所有的关联商品
        Integer parentId = orderInfoMapper.selectOrderInfoByOrderId(orderId).getParentId();//主项当前子订单对应的主订单Id
        List<OrderAssociated> mainOrderAssociatedList = orderAssociatedMapper.selectByOrderId(parentId.longValue());//查询主订单所有的关联商品
        for (OrderAssociated orderAssociated : orderAssociatedList) {
            for (OrderAssociated associated : mainOrderAssociatedList) {
                if (orderAssociated.getShopId().equals(associated.getShopId())) {
                    int difference = associated.getCount() - orderAssociated.getCount();
                    if (difference == 0) {
                        orderAssociatedMapper.deleteByPrimaryKey(associated.getOrderAssociatedId());
                    } else {
                        OrderAssociated newOrderAssociated = new OrderAssociated();
                        BeanUtils.copyProperties(associated, newOrderAssociated);
                        newOrderAssociated.setCount(difference);
                        orderAssociatedMapper.updateByPrimaryKey(newOrderAssociated);
                    }
                }
            }

        }
        orderAssociatedMapper.deleteByOrderId(orderId);
        orderInfoMapper.deleteOrderInfoByOrderId(orderId);
        countAndUpdateAmount(parentId.longValue());
    }
}
